import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MovieDAO {
    /**
     * 添加电影
     */
    public static void addMovie(Movie movie) {
        String sql = "INSERT INTO movies (id, name, director, actors, introduction, duration, rating) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?)";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, movie.getId());
            pstmt.setString(2, movie.getName());
            pstmt.setString(3, movie.getDirector());
            pstmt.setString(4, movie.getActors());
            pstmt.setString(5, movie.getIntroduction());
            pstmt.setInt(6, movie.getDuration());
            pstmt.setDouble(7, movie.getRating());

            pstmt.executeUpdate();
        } catch (SQLException e) {
            System.err.println("添加电影失败: " + e.getMessage());
            throw new RuntimeException("添加电影失败", e);
        }
    }

    /**
     * 获取所有电影
     */
    public static List<Movie> getAllMovies() {
        List<Movie> movies = new ArrayList<>();
        String sql = "SELECT * FROM movies";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                Movie movie = new Movie(
                        rs.getString("id"),
                        rs.getString("name"),
                        rs.getString("director"),
                        rs.getString("actors"),
                        rs.getString("introduction"),
                        rs.getInt("duration"),
                        rs.getDouble("rating")
                );
                movies.add(movie);
            }
        } catch (SQLException e) {
            System.err.println("查询所有电影失败: " + e.getMessage());
        }
        return movies;
    }

    /**
     * 根据ID查询电影
     */
    public static Movie getMovieById(String id) {
        String sql = "SELECT * FROM movies WHERE id = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, id);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                return new Movie(
                        rs.getString("id"),
                        rs.getString("name"),
                        rs.getString("director"),
                        rs.getString("actors"),
                        rs.getString("introduction"),
                        rs.getInt("duration"),
                        rs.getDouble("rating")
                );
            }
        } catch (SQLException e) {
            System.err.println("查询电影失败: " + e.getMessage());
        }
        return null;
    }
}
